home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 8904 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.3 KB

  1. Path: ix.netcom.com!news
  2. From: Norman Bullen <nbullen@ix.netcom.com>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: function to format float number
  5. Date: Wed, 06 Mar 1996 19:52:15 -0800
  6. Organization: Black Cat Associates
  7. Message-ID: <313E5D6F.4FD6@ix.netcom.com>
  8. References: <367cc$0321.121@news.express.ca>
  9. NNTP-Posting-Host: ple-ca9-19.ix.netcom.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-NETCOM-Date: Wed Mar 06  9:49:34 PM CST 1996
  14. X-Mailer: Mozilla 2.0 (Win16; I)
  15.  
  16. Gary Chan wrote:
  17. > I need a function to convert a floating point number to a formatted
  18. > dollar value string.  Eg.  1234 becomes $1,234.00
  19. > *******************
  20. > Thanks in advance. 
  21. Are you really sure you want to store dollar values in a float (or even 
  22. double) variable? Neither one can EXACTLY represent a value of 0.01! 
  23. Those round-off errors can really add up. I would suggest you use int or 
  24. long (depending upon the maximum value you need) and store number of 
  25. CENTs.
  26. In that case your function might be:
  27. void cformat(long n, char *buff)
  28. {  int i;
  29.    i = sprintf(buff, "%03ld", n);
  30.    buff[i+2] = '\0'; 
  31.    buff[i+1] = buff[i-1]; i--;
  32.    buff[i+1] = buff[i-1]; i--;
  33.    buff[i+1] = '.';
  34.    while (i>0) {
  35.       buff[i] = buff[i-1]; i--;
  36.                }
  37.    buff[0] = '$';
  38. }
  39.  
  40. I didn't put in code to insert commas; something left for you to do.
  41.